//
//  PersonalInformationViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 27/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import PromiseKit
import SwiftyJSON
import Dollar
import Alamofire

class ContactInformationViewController: BaseViewController {

    let formData = [
        "Name",
        "Contact No.",
    ]
    let formTitle = ["Father's ", "Mother's ", "Colleague's ", "Spouse's "]
    @IBOutlet weak var saveButtonView: FooterButtonView!
    @IBOutlet weak var baseTableView: UITableView!
    var userContactInfoArr: [UserContactInfo] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Contact information"
        baseTableView.register(cellType: InputTableViewCell.self)
        baseTableView.tableFooterView = UIView()
        // Do any additional setup after loading the view.
        saveButtonView.doneButton.setBlockFor(.touchUpInside) {[weak self] (button) in
            EZAlertController.alert("Save information", message: "Whether to save the modified information？", buttons: ["Give up", "Save"], tapBlock: { (_, index) in
                if index == 1 {
                    var postArr: [[String: Any]] = [];
                    Dollar.each((self?.userContactInfoArr)!){ (index, item) in
                        item.relationShip = index + 1;
                        item.userId = appUser.userId!;
                        postArr.append(item.toDictionary());
                    }
                    
                    let request = RequestData(path: "User/EditUserContactInfoV2", method: .post, paramArr: postArr)
                    netRequest(request).then{ _ in
                        nowNavgationController.popViewController(animated: true)
                    }
                    
                  /*  var request = URLRequest(url: URL(string: kRootServerURL + "User/EditUserContactInfoV2")!)
                    request.httpMethod = "POST"
                    request.setValue("iOS", forHTTPHeaderField: "qudao")
                    request.setValue("1", forHTTPHeaderField: "version")
                    request.setValue("1", forHTTPHeaderField: "deviceNo")
                    request.setValue(appUser.token!, forHTTPHeaderField: "token")
                    request.setValue("\(appUser.userId!)", forHTTPHeaderField: "userId")
                    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                    request.httpBody = try! JSONSerialization.data(withJSONObject: postArr)
                    Alamofire.request(request)
                        .responseJSON { response in
                            // do whatever you want here
                            switch response.result {
                            case .failure(let error):
                                print(error)
                                if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
                                    print(responseString)
//                                    nowNavgationController.popViewController(animated: true)
                                }
                            case .success(let responseObject):
                                print(responseObject)
                                nowNavgationController.popViewController(animated: true)
                            }
                    } */
                }
            })
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return super.tableView(tableView, viewForHeaderInSection: section)
    }


    func saveData(_ tf: UITextField) {
        let section = tf.tag / 10
        let tag = tf.tag % 10
        switch tag {
        case 0:
            userContactInfoArr[section].relationUserName = tf.text!
        case 1:
            userContactInfoArr[section].phone = tf.text!
        default:
            break
        }
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
extension ContactInformationViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return formTitle.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return formData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: InputTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        let htmlText = "<span style=\"font-family: PingFang SC; font-size:14px;color: #888888\"><span style=\"color: #D0021B\">*</span>\(formTitle[indexPath.section])\(formData[indexPath.row])</span>";
        cell.fieldLabel.attributedText = htmlText.html2AttributedString
        cell.fieldTF.text = ""
        cell.fieldTF.delegate = self
        cell.fieldTF.tag = indexPath.section * 10 + indexPath.row
        cell.accessoryType = .none
        switch indexPath.row {
        case 0:
            cell.fieldTF.text = userContactInfoArr[indexPath.section].relationUserName
        case 1:
            cell.fieldTF.text = userContactInfoArr[indexPath.section].phone
        default:
            break
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = tableView.cellForRow(at: indexPath) as! InputTableViewCell
        cell.fieldTF.isEnabled = true
        cell.fieldTF.becomeFirstResponder()
//        func setOptions(_ string: String) {
//            let arr = appSelection.filter { (selection) -> Bool in
//                return selection.selectType == string
//            }
//            let opt = OptionsView(frame: appWindow.bounds)
//            opt.setWithOptions(arr)
//            appWindow.addSubview(opt)
//            opt.show()
//            opt.clickCallback = { [weak self] section -> Void in
//                cell.selection = section
//                cell.fieldTF.text = section.selectText
//                self?.saveData(cell.fieldTF)
//            }
//        }
//        switch indexPath.row {
//        case 0:
//            cell.fieldTF.resignFirstResponder()
//            cell.fieldTF.isEnabled = false
//            setOptions("relationship")
//        default:
//            break
//        }
        
        
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return formTitle[section] + "info"

    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        saveData(textField)
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        saveData(textField)
        return true
    }

}


